package com.flag.liutao.common.filter;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.flag.liutao.common.domain.LocalUser;
import com.flag.liutao.common.utils.JwtUtil;
import com.flag.liutao.common.utils.RedisUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.header.HeaderWriterFilter;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Component
@Slf4j
public class JwtFilter extends OncePerRequestFilter {

    @Autowired
    private RedisUtil redisUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        List<String> list = Arrays.asList(new String[]{"/api/login","/admin/login","/api/chptcha","/swagger-ui.html","/file/"});
        String requestURI = request.getRequestURI();
        for (String path : list) {
            if(requestURI.contains(path)){
                filterChain.doFilter(request,response);
                return;
            }
        }

        String authorization = request.getHeader("Authorization");
        if(StrUtil.isBlank(authorization)){
            filterChain.doFilter(request,response);
            log.info("token 不存在");
            return ;
        }
        String[] split = authorization.split(" ");
        if(split.length!=2 && !split[0].equals("Bearer")){
            filterChain.doFilter(request,response);
            log.info("token 格式错误");
            return ;
        }

        String token = split[1];
        String id;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            id = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token认证失败");
        }

        String str = "";
        if(requestURI.contains("/admin/")){
            str = redisUtil.getCacheObject("admin-login:" + id + token);
        }

        if(requestURI.contains("/api/")){
            str = redisUtil.getCacheObject("api-login:" + id + token);
        }



        LocalUser user = JSONObject.parseObject(str,LocalUser.class);
        if(ObjectUtil.isNull(user)){
            throw new RuntimeException("用户登录已过期");
        }

        //将从token 和redis 中获取的用户信息权限存入SecurityContextHolder中
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user,null,user.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request,response);

    }
}
